import { CustomPage } from '/engine/index';
import { getUserInfo } from '../../services/user';
import { updateConversation } from '../../services/chat';
import { calculateAge } from '../../utils/index';
import { conversationList } from '../../services/chat';

CustomPage({
  data: {
    userInfo: {},
    age: '',
    conversationHistory: [],
    top: 0,
    total: 0,
    page: 1,
    pageSize: 20,
  },
  async onShow() {
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    const userInfo = await getUserInfo();
    const conversationsList = await conversationList(
      this.data.page,
      this.data.pageSize
    );
    this.setData({
      userInfo: userInfo?.data,
      age: calculateAge(userInfo?.data?.birthday),
      top: menuButtonInfo.height + menuButtonInfo.top + 20,
      conversationHistory: conversationsList.rows,
      total: conversationsList.total,
    });
  },
  onClickBack() {
    const pages = getCurrentPages();

    // 计算 mine 页面在路由堆栈中出现的次数和位置
    const mineIndices = [];
    for (let i = 0; i < pages.length; i++) {
      if (pages[i].route === 'pages/mine/index') {
        mineIndices.push(i);
      }
    }

    // 如果 mine 页面出现多次
    if (mineIndices.length > 1) {
      // 获取第一次出现的 mine 页面的索引
      const firstMineIndex = mineIndices[0];

      // 如果第一个 mine 页面前面还有页面，则返回到那个页面
      if (firstMineIndex > 0) {
        const delta = pages.length - firstMineIndex;
        wx.navigateBack({ delta });
      } else {
        // 如果第一个 mine 页面是路由堆栈的第一个页面，则无法返回更前面的页面
        wx.navigateBack();
      }
    } else {
      // 如果 mine 页面只出现一次，则正常返回
      wx.navigateBack();
    }
  },
  onClickEdit() {
    wx.navigateTo({ url: '/pages/edit-profile/index' });
  },
  onClickSetting() {
    wx.navigateTo({ url: '/pages/setting/index' });
  },
  async onScrollBottom() {
    const hasMore = this.data.page * this.data.pageSize < this.data.total;
    if (hasMore) {
      const conversationsList = await conversationList(
        this.data.page + 1,
        this.data.pageSize
      );

      this.setData({
        conversationHistory: [
          ...this.data.conversationHistory,
          ...conversationsList.rows,
        ],
        page: this.data.page + 1,
      });
    }
  },
  async onNavigateToChat(event) {
    const params = event.currentTarget.dataset.item;
    await updateConversation({
      id: params.id,
      isRead: 0,
    });

    wx.navigateTo({
      url: `/pages/chat/index?type=history&chatId=${params.id}`,
    });
  },
  onClickNewChat() {
    wx.reLaunch({
      url: '/pages/chat/index?type=new',
    });
  },
});
